import React from 'react';
import {connect} from 'react-redux'
import { bindActionCreators } from 'redux'

import Loginstyle from './login.css'
import * as userinfoActions from '../../actions/userinfo'

class LoginChil extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            ws:'',
            username:''
        }
    }
    render(){
        return(
            <div className={Loginstyle.loginArea}>
                <div className={Loginstyle.login}>
                    <p><label htmlFor="username" className={Loginstyle.label}>输入用户名:</label></p>
                    <p><input value={this.state.username} type="text" id="username" className={Loginstyle.user} onChange={this.getUser.bind(this)}/></p>
                    <p><a className={Loginstyle.loginBtn} onClick={this.loginSetStore.bind(this)}>登录</a></p>
                </div>
            </div>
        )
    }
    getUser(e){
        this.setState({
            username:e.target.value
        })
    }
    loginSetStore(){
        const username = this.state.username;
        if(username==''){
            alert('请输入用户名')
        }else{
            this.props.actions.login({
                userid: username
            });
            //调用方法
            this.connectWs(username);
            // 跳转
            this.props.handleLogin();
        }
    }
    connectWs(name) {
        const ws = this.state.ws;
        this.props.actions.setobj({
            obj:ws
        })
        ws.send(JSON.stringify({
            type:'login',
            name: name
        }))
    }
    componentDidMount(){
        const user = this.props.username.userid==undefined?'':this.props.username.userid;
        this.setState({
           username: user
        });
        this.state.ws = new WebSocket(this.props.path.path=='ws://192.168.196.91:9502'?this.props.path.path:'ws://192.168.196.91:9502');
        const ws = this.state.ws;
        ws.onopen = function(){
           alert(1)
        }

    }
}

function mapStateToProps(state){
    return{
        username:state.username,
        ws:state.objws,
        path:state.path
    }
}
function mapDispatchToProps(dispatch){
    return{
        actions: bindActionCreators(userinfoActions,dispatch)
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(LoginChil)
